import { initPage } from './utils/puppeteerFunc';
import * as http from 'http';
import { IncomingMessage, ServerResponse } from 'http';
import { URL } from 'url';

const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
    if (req.method !== 'GET') {
        sendJsonResponse(res, 405, { error: '方法不允许' });
        return;
    }

    const url = new URL(req.url || '', `http://${req.headers.host}`);
    const link = url.searchParams.get('link');

    if (!link) {
        sendJsonResponse(res, 400, { error: '缺少 link 参数' });
        return;
    }

    try {
        const images = await scrapeImages(link);
        sendJsonResponse(res, 200, { images });
    } catch (error) {
        console.error('处理请求时出错:', error);
        sendJsonResponse(res, 500, { error: '服务器内部错误' });
    }
};

const scrapeImages = async (link: string): Promise<string[]> => {
    const page = await initPage();
    await page.goto(link);
    await page.waitForSelector('#detail .tab-con > div');

    const images = await page.evaluate(() => {
        const imgElements = document.querySelectorAll('#detail .tab-con > div')[0].querySelectorAll('img');
        return Array.from(imgElements).map((img: Element) => (img as HTMLImageElement).src);
    });

    await page.close();
    return images;
};

const sendJsonResponse = (res: ServerResponse, statusCode: number, data: object) => {
    res.writeHead(statusCode, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(data));
};

const server = http.createServer(handleRequest);

const PORT = 3000;
server.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});
